<?php
/**
 * @file $HeadURL: tag.php $
 * @author $Author: LiangJian (liangjian@haibao.com) $
 * @date $Date: 2014-11-11 下午12:38:39 $
 * @brief 
 */
namespace haibao\www\data;
use \haibao\www\model\filter\Tag as TagFilter;
use \haibao\www\model\data\Tag as TagData;
use \haibao\frame\data\query\Condition;

class Tag extends \haibao\www\data\BaseMysql{
	private static $xcacheTagDictName = 'TAG_DICT';
	private static $xcacheTagAllNameNoStruct = 'TAG_ALL_NAME_NoStruct';
	private static $xcacheTagAllNameHavStruct = 'TAG_ALL_NAME_HavStruct';
	private static $xcacheTagTreeName = 'TAG_TREE';
	private static $xcacheTagChannelDictName = 'TAG_CHANNEL_DICT';
	private static $xcacheTagChannelTreeName = 'TAG_CHANNEL_TREE';
	
	
	public function __construct(){
		parent::__construct('\haibao\www\model\data\Tag');
		$this->setConfig(\haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE);
	}
	
	/**
	 * 根据标签id查询标签信息
	 * @param int $tagId
	 * @param boolean $detail 只显示基本信息
	 */
	public function getTagById($tagId, $brief = true){
		$cache = new \haibao\www\cache\Tag();
		$model = null;
		if ($brief){
		    $cacheTag = $cache->getTagById($tagId);
		    if ($cacheTag){
		        $model = new \haibao\www\model\data\Tag();
		        $model->loadArray($cacheTag);
		    }
		}
		if( empty($model) ){
		    $model = $this->getOneById($tagId);
		    $cache->setTagById($tagId, $model);
		}
		if($model && $model->Alias){
		    $model->Alias = trim($model->Alias,',');
		}
		return $model;
	}
	
	/**
	 * 根据多个标签id查询标签
	 * @param int or array 标签id
	 * @param array
	 */
	public function getTagsById($tagIds){
		$data = array();
		$tagIds = (array)$tagIds;
		if($tagIds) {
		    $cache = new \haibao\www\cache\Tag();
		    $data = $cache->getTagByIds($tagIds);
		    if(!$data){
    			$str = preg_replace('/(\d+)/', '%s', implode(',', $tagIds));
    			$sql = "select * from `tag`where tag_id in(".$str.")";
    			
    			$result = $this->query($sql, $tagIds);
    			$data = $tmp = array();
    			while ($result->fetch_assoc()){
    				$tmp = array();
    				$model = new \haibao\www\model\data\Tag();
    				foreach($model->getKeyMap() as $keyName=>$keyType){
    					if (!($keyType instanceof \haibao\frame\data\datafield\RelationOneField || $keyType instanceof \haibao\frame\data\datafield\RelationManyField)){
    						$tmp[$keyName] = $result->getData($keyType->getFieldName());
    					}
    					if($keyName == 'Alias' && $result->getData('alias')){
    						$tmp[$keyName] = trim($tmp[$keyName],',');
    					}
    				}
    				$data[$result->getData('tag_id')] = $tmp;
    			}
    			$cache->setTagByIds($tagIds, $data);
		    }
		}
		
		return $data;
	}
	
	public function getTagIdByName($tagName){
	    $tagId = 0;
	    $cache = new \haibao\www\cache\Tag();
	    $tagId = $cache->getTagIdByName($tagName);
	    if(!$tagId){
    	    $sql = "select tag_id from `tag` where tag_name=%s";
    	    $result = $this->query($sql, array($tagName));
    	    while ($result->fetch_assoc()){
    	        $tagId = $result->getData('tag_id');
    	    }
    	    $cache->setTagIdByName($tagName, $tagId);
	    }
	    return $tagId;
	}
	
	/**
	 * @param \haibao\www\model\data\Tag $model
	 */
	public function addTag($model){
		$this->beginTranscation();
		try {
			$this->add($model);
			$this->addKeywords($model);
			$this->clearCache();
		} catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	/**
	 * @param \haibao\www\model\data\Tag $model
	 */
	public function updateTagById($model){
		$this->beginTranscation();
		try {
			$this->updateById($model->Id, array(
					TagFilter::CONDITION_FIELD_NAME_TAG_NAME => $model->TagName,
					TagFilter::CONDITION_FIELD_NAME_ALIAS => $model->Alias,
					TagFilter::CONDITION_FIELD_NAME_QUANPIN => $model->QuanPin,
					TagFilter::CONDITION_FIELD_NAME_JIANPIN => $model->JianPin,
					TagFilter::CONDITION_FIELD_NAME_TAG_TYPE => $model->TagType,
					TagFilter::CONDITION_FIELD_NAME_URL => $model->Url,
					TagFilter::CONDITION_FIELD_NAME_SUSER => $model->Suser,
					TagFilter::CONDITION_FIELD_NAME_LASTMODIFIED => $model->LastModified,
			));
			
			$this->deleteKeywords($model->Id);
			$this->addKeywords($model);
			
			$cache = new \haibao\www\cache\Tag();
			$cache->deleteTagById($model->Id);
			
			$this->clearCache();
		} catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	/**
	 * 转移标签
	 */
	public function moveTag($tagModel,$childIds,$oper){
		$this->beginTranscation();
		try {
			$this->updateById($tagModel->Id, array(
					TagFilter::CONDITION_FIELD_NAME_TOP_ID =>$tagModel->TopId,
					TagFilter::CONDITION_FIELD_NAME_TAG_LEVEL => $tagModel->TagLevel,
					TagFilter::CONDITION_FIELD_NAME_PARENT_ID => $tagModel->ParentId,
					TagFilter::CONDITION_FIELD_NAME_CREATOR => $tagModel->Creator,
					TagFilter::CONDITION_FIELD_NAME_LASTMODIFIED => $tagModel->LastModified
			));
			if($childIds){
				$levelWhere = '';
				$str = preg_replace('/(\d+)/', '%s', implode(',', $childIds));
				if($oper){
					$levelWhere = ",tag_level = tag_level".$oper;
				}
				$sql = 'update tag set top_id =%s'.$levelWhere.',creator=%s,lastmodified=%s where tag_id in ('.$str.')';
				$param = array($tagModel->TopId,$tagModel->Creator, $tagModel->LastModified);
				$this->query($sql,array_merge($param,$childIds));
			}
			$cache = new \haibao\www\cache\Tag();
			$cache->deleteTagById($tagModel->Id);
            $this->clearCache();
		} catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	/**
	 * 删除标签（软删除）
	 */
	public function deleteTagById($tagId){
		$this->beginTranscation();
		try {
			$tagIdArr = $this->getChildrenTreeByTagId($tagId);
			$tagIds = (array)$this->multiarray_keys($tagIdArr, TagFilter::CONDITION_FIELD_NAME_ID);
			$tagIdStr = implode(',', $tagIds);
			
			$str = preg_replace('/(\d+)/', '%s', $tagIdStr);
			$sql = 'update tag set tag_status=%s where tag_id in ('.$str.')';
			
			$aParam = $tagIds;
			array_unshift($aParam, TagData::STATUS_DISABLE);
			$this->query($sql, $aParam);
			
			$this->deleteKeywords($tagIds);
			
			$cache = new \haibao\www\cache\Tag();
			$cache->deleteTagById($tagId);
			
			$this->clearCache();
		} catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	/**
	 * 修改顶级标签树的top_id
	 */
	public function updateTagTopId($tagId){
		$this->updateById($tagId, array(
			\haibao\www\model\filter\Tag::CONDITION_FIELD_NAME_TOP_ID => $tagId
		));
		
		$cache = new \haibao\www\cache\Tag();
		$cache->deleteTagById($tagId);
	}
	
	/**
	 * 添加标签和标签别名到keyword表中
	 * @param \haibao\www\model\data\Tag $model
	 */
	public function addKeywords($model){
		$sql = 'insert into tag_keywords(tag_id, kw_name, url, p_id, kw_length) values ';
		$arrSql = $arrValues = array();
		
		$existOfKeyword = $this->getExistTag($model->TagName);
		
		if( empty($existOfKeyword) ){
			array_push($arrSql, '(%s,%s,%s,%s,%s)');
			array_push($arrValues, $model->Id);
			array_push($arrValues, $model->TagName);
			array_push($arrValues, $model->Url);
			array_push($arrValues, 0);	// 这里主标签的p_id存成0
			array_push($arrValues, strlen($model->TagName));
// 			array_push($arrValues, $this->getLanguageType($model->Id, $model->TagName, $model->TopId));
		}
		
		if( $model->Alias ){
			$aAlias = explode(',', $model->Alias);
			foreach($aAlias as $tag){
				if($tag == $model->TagName){
					continue;
				}
				array_push($arrSql, '(%s,%s,%s,%s,%s)');
				array_push($arrValues, $model->Id);
				array_push($arrValues, $tag);
				array_push($arrValues, $model->Url);
				array_push($arrValues, $model->ParentId);
				array_push($arrValues, strlen($tag));
// 				array_push($arrValues, $this->getLanguageType($model->Id, $tag, $model->TopId));
			}
		}
		if($arrSql && $arrValues){
			$sql .= implode(',', $arrSql);
			$this->query($sql, $arrValues);
		}
	}
	
	/**
	 * 获取明星或品牌标签的语言类型
	 * @param int $tagId 标签id
	 * @param string $tagName 标签名
	 * @param int $topId 顶级标签id
	 * @return number 1：中文、2：英文
	 */
	private function getLanguageType($tagId, $tagName, $topId){
// 		if($topId == \haibao\www\model\data\Tag::BRAND_TAG_ID){
// 			$table = 'library_brand';
// 		} elseif($topId == \haibao\www\model\data\Tag::CELEBRITY_TAG_ID) {
// 			$table = 'library_celebrity';
// 		} else {
// 			return 0;
// 		}
// 		$sql = "select name_ch,name_en from $table where tag_id=%s limit 1";
// 		$result = $this->query($sql, array($tagId));
// 		while ($result->fetch_assoc()){
// 			$name_ch = $result->getData('name_ch');
// 			$name_en = $result->getData('name_en');
// 		}
		
// 		$languageType = 0;
// 		if($name_ch == $tagName){
// 			return 1;
// 		} elseif($name_en == $tagName) {
// 			return 2;
// 		} else {
// 			return 0;
// 		}
	}
	
	/**
	 * 返回已经存在的标签名
	 * @return array 存在返回标签数组，不存在返回不存在的array()
	 */
	public function getKeywordByName($arrKeyword){
		$data = $aTempTag = $aTempKeyWord = array();
		$len = count($arrKeyword);
		for($i=0;$i<$len;$i++){
			array_push($aTempTag, "tag_name=%s");
			array_push($aTempKeyWord, "kw_name=%s");
		}
		
		$sql = 'select tag_name from tag where tag_status=%s '.($aTempTag ? ' and '.implode(' or ', $aTempTag) : '') . ' union '. 'select kw_name from tag_keywords '.($aTempKeyWord ? 'where '.implode(' or ', $aTempKeyWord) : '');
		
		$aParam = array_unshift(array_merge($arrKeyword, $arrKeyword), \haibao\www\model\data\Tag::STATUS_ENABLE);
		$result = $this->query($sql, $aParam);
		while ($result->fetch_assoc()){
			array_push($data, $result->getData('tag_name'));
		}
		return $data;
	}
	
	/**
	 * 获取顶级标签，不包括推广
	 */
	public function getTopTag(){
		$filter = new TagFilter();
		$filter->select(array(
				TagFilter::CONDITION_FIELD_NAME_ID,
				TagFilter::CONDITION_FIELD_NAME_TAG_NAME,
				TagFilter::CONDITION_FIELD_NAME_URL
			));
		$filter->where(TagFilter::CONDITION_FIELD_NAME_PARENT_ID, Condition::CONDITION_EQUAL, TagData::TOP_PARENT_ID);
		$filter->where(TagFilter::CONDITION_FIELD_NAME_TAG_STATUS, Condition::CONDITION_EQUAL, TagData::STATUS_ENABLE);
		$filter->where(TagFilter::CONDITION_FIELD_NAME_ID, Condition::CONDITION_EQUAL, TagFilter::CONDITION_FIELD_NAME_TOP_ID, $filter, $filter);
		$filter->where(TagFilter::CONDITION_FIELD_NAME_ID, Condition::CONDITION_NOTEQUAL, TagData::SPREAD_TAG_ID);
		$filter->order(TagFilter::CONDITION_FIELD_NAME_CREATETIME, true);
		
		return $this->getAll($filter);
	}
	
	/**
	 * @param string $tagName 标签名
	 * @param int $tagId 需要排除的标签id
	 */
	public function getTagByTagName($tagName, $tagId = null){
		$model = null;
		$sql = 'select * from tag where (tag_name=%s or alias=%s) and tag_status=%s';
		$aParam = array($tagName, $tagName, \haibao\www\model\data\Tag::STATUS_ENABLE);
		
		if($tagId){
			$sql .= ' and tag_id<>%s';
			array_push($aParam, $tagId);
		}
		
		$result = $this->query($sql, $aParam);
		while ($result->fetch_assoc()){
			$model = new \haibao\www\model\data\Tag();
			foreach($model->getKeyMap() as $keyName=>$keyType){
				$model->$keyName = $result->getData($keyType->getFieldName());
			}
		}
		return $model;
    }

    public function getTagsByName($search)
    {
        $data = array();
        if (empty($search)) {
            $result = $this->query("select tag_id,tag_name,alias from `tag` order by tag_id desc limit 10");
        } else {
            $sql = "select tag_id,tag_name,alias from `tag` where (tag_name like %s or alias like %s or tag_id=%s) and tag_status=%s ORDER BY  REPLACE(tag_name,%s,'')  limit 30";
            $searchLike = '%' . $search . '%';
            $result = $this->query($sql, array(
			$searchLike, $searchLike, $search, TagData::STATUS_ENABLE,$search
		));
		}
		while ($result->fetch_assoc()){
			$tagId = $result->getData('tag_id');
			$data[$tagId] = $result->getData('tag_name');
		}
		return $data;
	}
	
	public function deleteKeywords($tagIds){
		$tagIds = (array)$tagIds;
		$tagIdStr = implode(',', $tagIds);
		$str = preg_replace('/(\d+)/', '%s', $tagIdStr);
		$this->query("delete from tag_keywords where tag_id in ({$str})", $tagIds);
	}
	
	/**
	 * 获取最大的topic_id值
	 */
	public function getMaxTopicId(){
		$max = null;
		$result = $this->query("select max(topic_id) as max from tag");
		while ($result->fetch_assoc()) {
			$max = $result->getData('max');
		}
		return $max;
	}
	
	/**
	 * 根据TopicId查询标签id
	 * @param int or array $arrId
	 * @return array
	 */
	public function getTopicIdByTagId($arrId){
		$data = array();
		$arrId = (array)$arrId;
		/* $cacheTagDict = $this->getAllTagDict();
		if($cacheTagDict && $arrId){
			foreach ($arrId as $tagId){
				isset($cacheTagDict[$tagId]) ? $data[$tagId] = $cacheTagDict[$tagId]['TopicId'] : 0;
			}
		}else */
		if($arrId){
			$str = preg_replace('/(\d+)/', '%s', implode(',', $arrId));
			$sql = "select `tag_id`,`topic_id` from `tag`where tag_id in({$str})";
			$result = $this->query($sql, $arrId);
			$data = array();
			while ($result->fetch_assoc()){
				$data[$result->getData('tag_id')] = $result->getData('topic_id');
			}
		}
		return $data;
		
	}
	
	/**
	 * 根据tag_id查询topic_id
	 * @param int or array $arrTagId
	 */
	public function getTagIdByTopicId($arrTagId){
		$arrTagId = (array)$arrTagId;
		$str = preg_replace('/(\d+)/', '%s', implode(',', $arrTagId));
		$sql = "select `tag_id`,`topic_id` from `tag` where topic_id in({$str})";
		$result = $this->query($sql, $arrTagId);
		$data = array();
		while ($result->fetch_assoc()){
			$data[$result->getData('topic_id')] = $result->getData('tag_id');
		}
		return $data;
	}
	
	/**
	 * 获取所有标签摘要信息
	 * @return array(TagId=>array(TagName,ParentId))
	 */
	public function getAllTagDict(){
		$cacheTagArr = $this->getCache(self::$xcacheTagDictName);
		return $cacheTagArr ? $cacheTagArr : $this->setAllTagDict();
	}
	
	public function getAllTagName($isMatchNoStruct = false){
		if($isMatchNoStruct){
			$cacheName = self::$xcacheTagAllNameHavStruct;
		}else{
			$cacheName = self::$xcacheTagAllNameNoStruct;
		}
		$cacheTagArr = $this->getCache($cacheName);
		if(empty($cacheTagArr)){
			$allTagDict = $this->getAllTagDict();
			foreach ($allTagDict as $key=>$tag){
				if(!$isMatchNoStruct){
					if($tag['TopId'] != \haibao\www\model\data\Tag::STRUCTURE_TAG){
						$cacheTagArr[$tag['Id']] = $tag['TagName'];
					}
				}elseif($tag['Id'] != \haibao\www\model\data\Tag::STRUCTURE_TAG){
					$cacheTagArr[$tag['Id']] = $tag['TagName'];
				}
			}
			$this->setCache($cacheName, $cacheTagArr);
		} else {
			return $cacheTagArr;
		}
		return $cacheTagArr;
	}
	
	/**
	 * 获取频道结构标签摘要信息
	 * @return array(TagId=>array(TagName,ParentId))
	 */
	public function getAllTagChannelDict(){
		$cacheTagArr = $this->getCache(self::$xcacheTagChannelDictName);
		return $cacheTagArr ? $cacheTagArr : $this->setAllTagChannelDict();
	}
	/**
	 * 获取所有标签树或某顶级标签下的所有标签
	 */
	public function getTagTree($topId = null){
		/* $cacheTagTree = null;
		if($topId == 5){
			$cacheTagTree = $this->getCache(self::$xcacheTagChannelTreeName);
		}else{
			$cacheTagTree = $this->getCache(self::$xcacheTagTreeName);
		}
		$tagTree = $cacheTagTree ? $cacheTagTree :($topId == 5 ? $this->setTagChannelTree():$this->setTagTree());
		if( isset($topId) && $topId !=5){
			$retTree = $tagTree[intval($topId)];
			return !empty($retTree) ? array($topId => $retTree) : null;
		} else {
			return $tagTree;
		} */
	    if($topId == 5){
	        $tagTree = $this->getCache(self::$xcacheTagChannelTreeName);
	        return $tagTree ? $tagTree : $this->setTagChannelTree();
	    }else{
	        $retTree = $this->getCache(self::$xcacheTagTreeName.$topId);
		    if(!$retTree){
		        $tagTree = $this->setTagTree();
		        $retTree = $tagTree[intval($topId)];
		    }
	    
	        return !empty($retTree) ? array($topId => $retTree) : null;
	    }
	}
	/**
	 * 获取频道结构标签树下的标签
	 */
	public function getLevelTagTree(){
		$cacheTagTree = $this->getCache(self::$xcacheLevelTagTreeName);
		$tagTree = $cacheTagTree ? $cacheTagTree : $this->setTagLevelTree();
		return $tagTree;
	}
	/**
	 * 根据标签id查找父级标签树
	 * @param \haibao\www\model\data\Tag $model
	 */
	public function getParentsTagArr($tagId){
		static $tagDictArr = array();
		$tagInfo = $this->getTagById($tagId);
		if($tagInfo){
			$tagDictArr[$tagId] = $tagInfo;
			if($tagInfo->ParentId != \haibao\www\model\data\Tag::TOP_PARENT_ID){
				$this->getParentsTagArr($tagInfo->ParentId);
			}
		}
		return $tagDictArr;
	}
	
	/**
	 * 根据标签id查找子级标签树（包含当前标签，当前标签为要查询的顶级标签）
	 * @param \haibao\www\model\data\Tag $model
	 */
	public function getChildrenTreeByTagId($tagId){
		$tagInfo = $this->getTagById($tagId);
		$tagParentArr = $this->getParentsTagArr($tagId);
		$arrTree = $this->getTagTree($tagInfo->TopId);
		while (count($tagParentArr)){
			$model = array_pop($tagParentArr);
			if($model->ParentId == \haibao\www\model\data\Tag::TOP_PARENT_ID && isset($arrTree[$model->Id]['children'])){
				$arrTree = $arrTree[$model->Id]['children'];
			}else{
				if(isset($arrTree[$model->Id]['children'])){
                    $arrTree = $arrTree[$model->Id]['children'];
                }else{
                    if(isset($arrTree[$model->Id])){
                        $arrTree = array($model->Id => $arrTree[$model->Id]);
                    }
                }
                //$arrTree = isset($arrTree[$model->Id]['children']) ? $arrTree[$model->Id]['children'] : array($model->Id => $arrTree[$model->Id]);
			}
		}
		if(is_array($arrTree) && $tagInfo->Id == key($arrTree)){
			return $arrTree;
		} else {
			$retTag = $tagInfo->toArray();
			$retTag['children'] = $arrTree;
			return array($tagInfo->Id => $retTag);
		}
	}
	
	public function getExistTag($aliases, $tagId = null){
		$param = array();
		if(is_array($aliases)){
			foreach($aliases as $alias){
				array_push($param,'%s');
			}
			$where = 'where kw_name in (' . implode($param,',') . ')';
		} else {
			$where = ' where kw_name in (%s)';
		}
		$where .= $tagId ? ' and tag_id<>'.$tagId : '';
		$sql = 'select kw_name from tag_keywords '.$where.' limit 1';
		
		$result = $this->query($sql, is_array($aliases) ? $aliases : array($aliases));
		if ($result->fetch_assoc()){
			return $result->getData('kw_name');
		}
	}
	
	/**
	 * 是否存在子分类
	 * @param int $tagId
	 */
	public function isExitstChildTag($tagId){
		$sql = "select * from `tag` where parent_id=%s and tag_status=%s";
		$result = $this->query($sql, array(intval($tagId),\haibao\www\model\data\Tag::STATUS_ENABLE));
		$data = array();
		while ($row = $result->fetch_assoc()){
			$model = new \haibao\www\model\data\Tag();
			$model->loadArray($row);
			array_push($data, $model);
		}
		return count($data);
	}
	/**
	 * 获取所有子分类的iD
	 */
	public function getChildIdsByTagId($tagId){
		$sql = "select * from `tag` where parent_id=%s and tag_status=%s";
		$result = $this->query($sql, array(intval($tagId),\haibao\www\model\data\Tag::STATUS_ENABLE));
		$tagIds = array();
		while ($row = $result->fetch_assoc()){
			array_push($tagIds,$result->getData('tag_id'));
		}
		return $tagIds;
	}
	/**
	 * 根据标签id找到所有所属子标签的树结构数组
	 */
	private function findChildrenTagTree($tagId, $tagTreeArr){
		static $retChildArr = array();
		foreach ($tagTreeArr as $key => $tree) {
			if($tree[TagFilter::CONDITION_FIELD_NAME_ID] == $tagId){
				$retChildArr = $tagTreeArr[$tagId];
			} else {
				if(isset($tree['children'])){
					$retChildArr = $this->findChildrenTagTree($tagId, $tree['children']);
				}
			}
		}
		return $retChildArr;
	}
	
	/**
	 * 生成标签树结构数组
	 * @param $return 是否需要返回值
	 */
	private function setTagTree($return = true){
		$tagTree = array();
		$allTagDict = $this->getAllTagDict();
		foreach($allTagDict as $key=>$tag){
			if(isset($allTagDict[$tag[TagFilter::CONDITION_FIELD_NAME_PARENT_ID]])){
				$allTagDict[$tag[TagFilter::CONDITION_FIELD_NAME_PARENT_ID]]['children'][$tag[TagFilter::CONDITION_FIELD_NAME_ID]] = &$allTagDict[$tag[TagFilter::CONDITION_FIELD_NAME_ID]];
			}else{
				$tagTree[$tag[TagFilter::CONDITION_FIELD_NAME_ID]] = &$allTagDict[$tag[TagFilter::CONDITION_FIELD_NAME_ID]];
			}
		}
		if($tagTree){
		    foreach($tagTree as $topId=>$tree){
		        $this->setCache(self::$xcacheTagTreeName.$topId, $tagTree[$topId]);
		    }
		}
		if($return){
			return $tagTree;
		}
	}
	/**
	 * 获取父级频道标签树
	 */
	public function getParentsChannelTree($parentsTagArr){
		$parentsTagTree = array();
		if($parentsTagArr){
			foreach($parentsTagArr as $key=>$tag){
				if(isset($parentsTagArr[$tag[TagFilter::CONDITION_FIELD_NAME_PARENT_ID]])){
					$parentsTagArr[$tag[TagFilter::CONDITION_FIELD_NAME_PARENT_ID]]['children'][$tag[TagFilter::CONDITION_FIELD_NAME_ID]] = &$parentsTagArr[$tag[TagFilter::CONDITION_FIELD_NAME_ID]];
				}else{
					$parentsTagTree[$tag[TagFilter::CONDITION_FIELD_NAME_ID]] = &$parentsTagArr[$tag[TagFilter::CONDITION_FIELD_NAME_ID]];
				}
			}
		}
		return 	$parentsTagTree;
	} 
	/**
	 * 生成频道结构标签树
	 * @param $return 是否需要返回值
	 */
	private function setTagChannelTree($return = true){
		$tagTree = array();
		$allTagDict = $this->getAllTagChannelDict();
		foreach($allTagDict as $key=>$tag){
			if(isset($allTagDict[$tag[TagFilter::CONDITION_FIELD_NAME_PARENT_ID]])){
				$allTagDict[$tag[TagFilter::CONDITION_FIELD_NAME_PARENT_ID]]['children'][$tag[TagFilter::CONDITION_FIELD_NAME_ID]] = &$allTagDict[$tag[TagFilter::CONDITION_FIELD_NAME_ID]];
			}else{
				$tagTree[$tag[TagFilter::CONDITION_FIELD_NAME_ID]] = &$allTagDict[$tag[TagFilter::CONDITION_FIELD_NAME_ID]];
			}
		}
		$tagTree && $this->setCache(self::$xcacheTagChannelTreeName, $tagTree);
		if($return){
			return $tagTree;
		}
	}
	/**
	 * 获取数据表中的所有可用标签保存到xcache中
	 * @param $return 是否需要返回值
	 */
	private function setAllTagDict($return = true){
		$arrDict = array();
		$sql = 'select tag_id,tag_name,parent_id,tag_level,alias,top_id,url,topic_id,tag_type,tag_status from tag where tag_status!= %s';
		$result = $this->query($sql, array(\haibao\www\model\data\Tag::STATUS_DISABLE));
		while ($result->fetch_assoc()){
				
			$tagId = $result->getData('tag_id');
			$arrDict[$tagId] = array(
					TagFilter::CONDITION_FIELD_NAME_ID => intval($tagId),
					TagFilter::CONDITION_FIELD_NAME_TOPIC_ID => intval($result->getData('topic_id')),
					TagFilter::CONDITION_FIELD_NAME_ALIAS =>trim($result->getData('alias'),'，'),
					TagFilter::CONDITION_FIELD_NAME_TAG_NAME => $result->getData('tag_name'),
					TagFilter::CONDITION_FIELD_NAME_PARENT_ID => intval($result->getData('parent_id')),
					TagFilter::CONDITION_FIELD_NAME_TOP_ID => intval($result->getData('top_id')),
					TagFilter::CONDITION_FIELD_NAME_TAG_LEVEL => intval($result->getData('tag_level')),
					TagFilter::CONDITION_FIELD_NAME_URL => $result->getData('url'),
					TagFilter::CONDITION_FIELD_NAME_TAG_TYPE => $result->getData('tag_type'),
					TagFilter::CONDITION_FIELD_NAME_TAG_STATUS=>$result->getData('tag_status')
			);
		}
		$this->setCache(self::$xcacheTagDictName, $arrDict);
		if($return){
			return $arrDict;
		}
	}
/**
	 * 获取数据表中的所有频道结构标签保存到xcache中
	 * @param $return 是否需要返回值
	 */
	private function setAllTagChannelDict($return = true){
		$arrDict = array();
		$sql = 'select tag_id,tag_name,parent_id,tag_level,top_id,url,topic_id from channeltab where tag_status=%s';
		$result = $this->query($sql, array(\haibao\www\model\data\Tag::STATUS_ENABLE));
			
		while ($result->fetch_assoc()){
			$tagId = $result->getData('tag_id');
			$arrDict[$tagId] = array(
					TagFilter::CONDITION_FIELD_NAME_ID => intval($tagId),
					TagFilter::CONDITION_FIELD_NAME_TOPIC_ID => intval($result->getData('topic_id')),
					TagFilter::CONDITION_FIELD_NAME_TAG_NAME => $result->getData('tag_name'),
					TagFilter::CONDITION_FIELD_NAME_PARENT_ID => intval($result->getData('parent_id')),
					TagFilter::CONDITION_FIELD_NAME_TOP_ID => intval($result->getData('top_id')),
					TagFilter::CONDITION_FIELD_NAME_TAG_LEVEL => intval($result->getData('tag_level')),
					TagFilter::CONDITION_FIELD_NAME_URL => $result->getData('url')
			);
		}
		$this->setCache(self::$xcacheTagChannelDictName, $arrDict);
		if($return){
			return $arrDict;
		}
	}
	/**
	 * 返回多维数组的指定值
	 * @param array $arr 要查找的数组
	 * @param string $strict 只返回该值的数组。
	 */
	private function multiarray_keys($arr, $strict){
		static $retArr = array();
		foreach ($arr as $key=>$val){
			array_push($retArr, $val[$strict]);
			if(isset($val['children'])){
				$this->multiarray_keys($val['children'], $strict);
			}
		}
		return $retArr;
	}
	
	/**
	 * 更新xcache中的标签和标签树
	 */
	public function clearCache(){
	    $topTag = $this->getTopTag();
	    if($topTag){
	        foreach($topTag as $key=>$tag){
	            $this->unsetCache(self::$xcacheTagTreeName.$tag->Id);
	        }
	    }
		$this->unsetCache(self::$xcacheTagDictName);
		$this->unsetCache(self::$xcacheTagTreeName);
	}
	
	/**
	 *@param string $content
	 *return array
	 */
	public function getTagsByRelationName($content,$isMatchNoStruct){
		$content = strtolower($content);
		$allTagDict = $this->getAllTagName($isMatchNoStruct);
		$relationTag = array();
		$pattern = array();
		$tagIds = array();
		$tagArr = array();
		if($allTagDict){
			foreach ($allTagDict as $key=>$tagName){
				if(strstr($content,strtolower($tagName))){
					$relationTag = array_merge($relationTag, $this->getParentsTagArr($key));
				}
			}
			foreach($relationTag as $k=>$v){
				if(!in_array($v->Id, $tagIds)){
					$tagIds[] = $v->Id;
					$tagArr[$k]['TagName'] = $v->TagName;
					$tagArr[$k]['Id'] = $v->Id;
					$tagArr[$k]['TopId'] = $v->TopId;
				}
			}
		}
		return $tagArr;
	}
}
